<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 商品分类级联选择器 -->
      <el-row class="margin">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="currentCategoriesId"
            :options="categoriesList"
            :props="categoriesProps"
            @change="categoryCascaderChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="tabsActiveName" @tab-click="tabsHandleClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParamsDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态表格 -->
          <el-table :data="tabsManyDatas" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTagParam(scope.row, index)"
                >
                  {{ item }}
                </el-tag>
                <!-- 添加标签 -->
                <el-input
                  class="input-new-tag margin"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParamsDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态表格 -->
          <el-table :data="tabsOnlyDatas" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTagParam(scope.row, index)"
                >
                  {{ item }}
                </el-tag>
                <!-- 添加标签 -->
                <el-input
                  class="input-new-tag margin"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParams(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数对话框 -->
      <el-dialog
        :title="'添加' + addDialogTitle"
        :visible.sync="addParamsDialogVisible"
        width="50%"
        @close="closeParamsDialog"
      >
        <el-form
          :model="addParamsForm"
          :rules="addParamsRules"
          ref="addParamsRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="addDialogTitle" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendAddParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数对话框 -->
      <el-dialog
        :title="'修改' + addDialogTitle"
        :visible.sync="editParamsDialogVisible"
        width="50%"
        @close="closeEditParamsDialog"
      >
        <el-form
          :model="editParamsForm"
          :rules="editParamsRules"
          ref="editParamsRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="addDialogTitle" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendEditParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  created () {
    this.getCategories()
  },
  data () {
    return {
      // 商品分类数据
      categoriesList: [],
      // 商品分类级联选择器选中项的 id 数组
      currentCategoriesId: [],
      // 商品分类级联选择器 props 配置
      categoriesProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // tab 栏选中项
      tabsActiveName: 'many',
      // 商品分类项的动态参数
      tabsManyDatas: [],
      // 商品分类项的静态参数
      tabsOnlyDatas: [],
      // 添加参数对话框开启和关闭
      addParamsDialogVisible: false,
      // 添加参数表单
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数表单验证规则
      addParamsRules: {
        attr_name: [
          {
            required: true,
            message: `请输入名称`,
            trigger: 'blur'
          }
        ]
      },
      // 修改参数对话框开启和关闭
      editParamsDialogVisible: false,
      // 修改参数表单
      editParamsForm: {
        attr_name: ''
      },
      // 修改参数表单验证规则
      editParamsRules: {
        attr_name: [
          {
            required: true,
            message: `请输入名称`,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    //   获取商品分类数据
    async getCategories () {
      let { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoriesList = res.data
    },
    // 商品分类级联选择器发生变化时
    categoryCascaderChange () {
      this.tabsActiveName = 'many'
      this.sendGetCategoryList()
    },
    // tab 栏切换事件
    tabsHandleClick () {
      this.sendGetCategoryList()
    },
    // 发送获取商品参数列表请求
    async sendGetCategoryList () {
      if (this.currentCategoriesId.length !== 3) {
        this.currentCategoriesId = []
        this.tabsManyDatas = []
        this.tabsOnlyDatas = []
        return
      }
      let { data: res } = await this.$http.get(
        `categories/${this.thirdCategoryId}/attributes`,
        {
          params: { sel: this.tabsActiveName }
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res.data)
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.tabsActiveName === 'many') {
        this.tabsManyDatas = res.data
      } else {
        this.tabsOnlyDatas = res.data
      }
    },
    // 关闭添加参数对话框
    closeParamsDialog () {
      this.$refs.addParamsRef.resetFields()
    },
    // 提交添加参数事件
    sendAddParams () {
      this.$refs.addParamsRef.validate(async (valid) => {
        if (!valid) return
        let { data: res } = await this.$http.post(
          `categories/${this.thirdCategoryId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.tabsActiveName
          }
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.sendGetCategoryList()
        this.addParamsDialogVisible = false
      })
    },
    // 点击修改按钮事件
    async editParams (id) {
      this.editParamsDialogVisible = true
      let { data: res } = await this.$http.get(
        `categories/${this.thirdCategoryId}/attributes/${id}`,
        { params: { attr_sel: this.tabsActiveName } }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editParamsForm = res.data
    },
    // 关闭添加参数对话框
    closeEditParamsDialog () {
      this.$refs.editParamsRef.resetFields()
    },
    // 点击确定按钮发送修改参数请求
    async sendEditParams () {
      this.$refs.editParamsRef.validate(async (valid) => {
        if (!valid) return
        let { data: res } = await this.$http.put(
          `categories/${this.thirdCategoryId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.tabsActiveName
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.sendGetCategoryList()
        this.editParamsDialogVisible = false
      })
    },
    // 点击删除参数按钮
    async deleteParams (id) {
      let confirm = await this.$messageBox
        .confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .catch((err) => err)
      if (confirm !== 'confirm') return this.$message.info('已取消删除')
      let { data: res } = await this.$http.delete(
        `categories/${this.thirdCategoryId}/attributes/${id}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.sendGetCategoryList()
    },
    // 添加标签失去焦点或按下回车事件
    async handleInputConfirm (row) {
      if (!row.inputValue.trim()) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      this.updateAttrVals(row)
    },
    // 点击 new tag 按钮事件
    showInput (row) {
      row.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 点击标签删除按钮
    deleteTagParam (row, index) {
      row.attr_vals.splice(index, 1)
      this.updateAttrVals(row)
    },
    // 更新attr_vals数据
    async updateAttrVals (row) {
      let { data: res } = await this.$http.put(
        `categories/${this.thirdCategoryId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      // this.sendGetCategoryList();
    }
  },
  computed: {
    // 商品分类参数面板添加按钮的控制
    isBtnDisabled () {
      if (this.currentCategoriesId.length !== 3) return true
      return false
    },
    // 商品分类级联选择器最后一级分类的 ID
    thirdCategoryId () {
      if (this.currentCategoriesId.length !== 3) return
      return this.currentCategoriesId[this.currentCategoriesId.length - 1]
    },
    // 添加分类对话框标题
    addDialogTitle () {
      if (this.tabsActiveName === 'many') return '动态参数'
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.margin {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 120px;
  margin: 5px;
}
.button-new-tag {
  margin: 5px;
}
</style>
